package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
     @Resource
     private StringRedisTemplate stringRedisTemplate;
     @Resource
     private CacheClient cacheClient;
     @Transactional
     @Override
    public Result update(Shop shop) {

        Long id=shop.getId();
        if (id == null) {
            return Result.fail("id不能为空");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        //返回
        return Result.ok();

    }
    @Override
    public Result queryById(Long id) {
        //缓存穿透返回空
//        Shop shop = cacheClient.queryWitPassThrough(
//                CACHE_SHOP_KEY,
//                id,
//                Shop.class,
//                this::getById,
//                CACHE_SHOP_TTL,
//                TimeUnit.MINUTES
//        );
        //
//        Shop shop = queryWitPassThrough(id);
//        if (shop != null) {
//            return Result.ok(shop);
//        }
        //互斥锁解决缓存击穿
//        Shop shop=queryWithMutex(id);
//        if (shop == null) {
//            return Result.fail("店铺不存在");
//        }
//        return Result.ok(shop);
        //逻辑过期解决缓存击穿
         Shop shop=cacheClient.queryWithLogicalExpire(
                 CACHE_SHOP_KEY,
                 id,
                 Shop.class,
                 this::getById,
                 20L,
                 TimeUnit.SECONDS          //逻辑过期时间
         );
        return Result.ok(shop);

    }
    //逻辑过期方法
    //建一个线程池




    public boolean tryLock(String key){
        Boolean flag=stringRedisTemplate.opsForValue().setIfAbsent(key,"1",10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    public void unLock(String key){
         stringRedisTemplate.delete(key);}
    public Shop queryWitPassThrough(Long id) {
        String key = CACHE_SHOP_KEY  + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //从redis中查询商铺缓存
        if(StringUtils.isNotBlank(shopJson)){
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        if(shopJson != null){
            return null;
        }
        //不存在，查询数据库
        Shop shop = getById(id);
        if(shop == null){
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //存在，写入redis并返回
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;

    }
    //互斥锁解决缓存击穿
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY  + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //从redis中查询商铺缓存
        if(StringUtils.isNotBlank(shopJson)){

            return JSONUtil.toBean(shopJson, Shop.class);
        }
        Shop shop = null;
        //是否是空值
        if(shopJson != null){
            return null;
        }
        //实现缓存重建
        String lockKey = "lock:shop:" + id;
        try {
            boolean isLock = tryLock(lockKey);
            if(!isLock){
                Thread.sleep(50);
                return queryWithMutex(id);

            }


            //成功，id查询数据库
            shop = getById(id);
            if(shop == null){
                stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //存在，写入redis并返回
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
            //释放锁释放锁

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            unLock(lockKey);

        }
        return shop;

    }


    //缓存店铺数据
    public void saveShop2Redis(Long id,Long expireTime) throws InterruptedException {
         Shop shop = getById(id);
         Thread.sleep(200);
         //逻辑过期时间
         RedisData redisData = new RedisData();
         redisData.setData(shop);
         redisData.setExpireTime(LocalDateTime.now().plusMinutes(expireTime));
         stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
        //写入redis

    }
}
